package com.example.pong;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;

import java.time.LocalTime;
import java.util.concurrent.Semaphore;

/**
 * @author Jim
 * @create 2025/1/10
 */
@SpringBootApplication
@Slf4j
public class PongServiceApplication {

    private static final int DELAY_TIME = 1000; // n毫秒后发
    public static void main(String[] args) {
        SpringApplication.run(PongServiceApplication.class, args);
    }
    @RestController
    class PongController {
        private final Semaphore semaphore = new Semaphore(1);

        @GetMapping("/pong")
        public Mono<String> getPongResponse() {
            //每次一条进入，其他(另外一个进程)失败
//            System.out.println("pong， time: " + LocalTime.now());
            if (semaphore.tryAcquire()) {
                return Mono.fromSupplier(() -> {
                    try {
                        //System.out.println("pong， 成功: " + LocalTime.now());
                        Thread.sleep(DELAY_TIME); // Simulate some processing delay
                        log.info("回复了:World======");
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                    }
                    semaphore.release();
                    return "World " + LocalTime.now();
                });
            } else {
                //System.out.println("Too many requests, please try again later" );
                return Mono.error(new RateLimitExceededException("Too many requests, please try again later"));
            }
        }
    }
}


